#include "process_pool.h"

#define FILENAME "bigfile.avi"

//sendn函数可以发送确定的字节数
int sendn(int sockfd, const void * buff, int len)
{
    int left = len;
    const char* pbuf = buff;
    int ret = -1;
    while(left > 0) {
        ret = send(sockfd, pbuf, left, 0);
        if(ret < 0) {
            perror("send");
            return -1;
        }
        left -= ret;
        pbuf += ret;
    }
    return len - left;
}

int transferFile(int peerfd)
{
    //读取本地文件
    int fd = open(FILENAME, O_RDONLY);
    ERROR_CHECK(fd, -1, "open");
    //获取文件的长度
    struct stat st;
    memset(&st, 0, sizeof(st));
    fstat(fd, &st);
    char buff[100] = {0};
    int filelength = st.st_size;
    printf("filelength: %d\n", filelength);

    //进行发送操作
    //1. 发送文件名
    train_t t;
    memset(&t, 0, sizeof(t));
    t.len = strlen(FILENAME);
    strcpy(t.buf, FILENAME);
    sendn(peerfd, &t, 4 + t.len);
    
    //2. 再发送文件内容
    //2.1 发送文件的长度
    sendn(peerfd, &filelength, sizeof(filelength));

    int ret = 0;
    int total = 0;
    //2.2 再发送文件内容
    while(total < filelength) {
        memset(&t, 0, sizeof(t));
        ret = read(fd, t.buf, 1000);
        if(ret > 0) {
            t.len = ret;
            //sendn函数确保 4 + t.len 个字节的数据能正常发送
            ret = sendn(peerfd, &t, 4 + t.len);
            if(ret < 0) {
                printf(">> exit while not send.\n");
                break;//发生了错误,就退出while循环
            }
            total += (ret - 4);
        }
    }

    return 0;
}

